package plus.easydo.starter.oauth.client.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import plus.easydo.starter.oauth.client.service.CustomizeClientServer;

import javax.annotation.Resource;


/**
 * openfeign微服务调用传递header信息 使用oAuth2RestTemplate获取token并传递
 * @author yuzhanfeng
 */
public class Oauth2FeignClientInterceptor implements RequestInterceptor {

    private static final String AUTHORIZATION_HEADER = "Authorization";

    private static final String BEARER_TOKEN_TYPE = "Bearer";

    @Resource
    private CustomizeClientServer customizeClientServer;

    @Override
    public void apply(RequestTemplate requestTemplate) {
//        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        if (requestAttributes != null) {
//            HttpServletRequest request = requestAttributes.getRequest();
//            Enumeration<String> headerNames = request.getHeaderNames();
//            if (headerNames != null) {
//                while (headerNames.hasMoreElements()) {
//                    String name = headerNames.nextElement();
//                    String values = request.getHeader(name);
//                    requestTemplate.header(name, values);
//                }
//            }
//            Enumeration<String> bodyNames = request.getParameterNames();
//            StringBuilder body = new StringBuilder();
//            if (bodyNames != null) {
//                while (bodyNames.hasMoreElements()) {
//                    String name = bodyNames.nextElement();
//                    String values = request.getParameter(name);
//                    body.append(name).append("=").append(values).append("&");
//                }
//            }
//            if(body.length()!=0) {
//                body.deleteCharAt(body.length()-1);
//                requestTemplate.body(body.toString());
//            }
            /*获取token信息并放到header中*/
            requestTemplate.header(AUTHORIZATION_HEADER,
                    String.format("%s %s",
                            BEARER_TOKEN_TYPE,
                            customizeClientServer.getAccessToken().getValue()));
//        }
    }
}
